package com.amigo.online.provider.user.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.amigo.online.common.base.security.LocalUser;
import com.amigo.online.common.core.response.Result;
import com.amigo.online.common.core.response.StatusCode;
import com.amigo.online.common.param.dto.activity.AddActivityDto;
import com.amigo.online.common.param.result.activity.ActivityInfo;
import com.amigo.online.common.param.result.activity.User;
import com.amigo.online.common.util.UploadTempUtil;
import com.amigo.online.provider.user.common.GlobalController;
import com.amigo.online.provider.user.exception.UserException;
import com.amigo.online.provider.user.mapper.*;
import com.amigo.online.provider.user.model.entity.*;
import com.amigo.online.provider.user.model.entity.collection.ActivityResPo;
import com.amigo.online.provider.user.model.entity.collection.ActivityTblPo;
import com.amigo.online.provider.user.model.entity.enums.ResEnum;
import com.amigo.online.provider.user.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author pangdonghao
 * @version 1.0
 * @csdn https://blog.csdn.net/pangdongh
 * @createDate 2019/11/07 10:52
 */
@Service
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    ActivityResTblMapper activityResTblMapper;
    @Autowired
    ActivityTblMapper activityTblMapper;
    @Autowired
    ActivityParticipateTblMapper activityParticipateTblMapper;
    @Autowired
    ActivityMapper activityMapper;
    @Autowired
    ActivityCoverTblMapper activityCoverTblMapper;
    @Autowired
    ActivityReadTblMapper activityReadTblMapper;



    /**
     * 添加活动
     * @param addActivityDto
     */
    @Override
    public void add(AddActivityDto addActivityDto) {
        ActivityTbl activityTbl = new ActivityTbl();
        activityTbl.setContent(addActivityDto.getContent());
        activityTbl.setUserId(LocalUser.getUser().getUser().getId());
        activityTbl.setLat(addActivityDto.getLat());//纬度
        activityTbl.setLng(addActivityDto.getLng());//经度
        activityTbl.setAddress(addActivityDto.getAddress());
        activityTblMapper.insertSelective(activityTbl);

        if(addActivityDto.getVideo()!=null){
            String url;
            try {
                url = UploadTempUtil.uploadImg(addActivityDto.getVideo(),LocalUser.getUser().getToken());
            } catch (IOException e) {
                e.printStackTrace();
                throw new UserException(StatusCode.INTERNAL_SERVER_ERROR);
            }
            ActivityResTbl activityResTbl = new ActivityResTbl();
            activityResTbl.setActivityId(activityTbl.getId());
            activityResTbl.setUrl(url);
            activityResTbl.setType(ResEnum.VIDEO.getValue());
            activityResTbl.setDuration(addActivityDto.getDuration());
            activityResTblMapper.insertSelective(activityResTbl);
        }
        if(addActivityDto.getPhotos()!=null){
            for (MultipartFile multipartFile :addActivityDto.getPhotos()){
                String url;
                try {
                    url = UploadTempUtil.uploadImg(multipartFile,LocalUser.getUser().getToken());
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new UserException(StatusCode.INTERNAL_SERVER_ERROR);
                }
                ActivityResTbl activityResTbl = new ActivityResTbl();
                activityResTbl.setActivityId(activityTbl.getId());
                activityResTbl.setUrl(url);
                activityResTbl.setType(ResEnum.IMAGE.getValue());
                activityResTblMapper.insertSelective(activityResTbl);
            }
        }
    }

    /**
     * 根据用户获取活动
     * @param userId
     * @param page
     * @return
     */
    @Override
    public List<ActivityInfo> getActivityByUserId(Long userId, Integer page) {
        Long userid = LocalUser.getUser().getUser().getId();
        List<ActivityTblPo> activityTblPos = activityMapper.selectByUser((page - 1) * 10, userId);
        List<ActivityInfo> result = JSONArray.parseArray(JSONArray.toJSONString(activityTblPos),ActivityInfo.class);
        for(int i=0;i<activityTblPos.size();i++){
            ActivityTblPo activityTblPo = activityTblPos.get(i);
            if(activityTblPo.getResList().size()>0 && activityTblPo.getResList().get(0).getType() == 2){//视频
                result.get(i).setVideoUrl(activityTblPo.getResList().get(0).getUrl());
                result.get(i).setDuration(activityTblPo.getResList().get(0).getDuration());
            }else {
                List<String> photos = new ArrayList<>();
                for (ActivityResPo activityResPo : activityTblPo.getResList()){
                    photos.add(activityResPo.getUrl());
                }
                result.get(i).setPhotos(photos);
            }
            if(activityTblPo.getCreatorId().equals(userid)){
                List<User> userList = activityMapper.selectActivityParticipate(activityTblPo.getId());
                result.get(i).setUserList(userList);
            }
        }

        return result;
    }

    /**
     * 获取最新活动
     * @param page
     * @return
     */
    @Override
    public Result<List<ActivityInfo>> getActivity(Integer page) {
        Long userid = LocalUser.getUser().getUser().getId();
        List<ActivityTblPo> activityTblPos = activityMapper.selectByUser((page - 1) * 10);
        List<ActivityInfo> result = JSONArray.parseArray(JSONArray.toJSONString(activityTblPos),ActivityInfo.class);
        for(int i=0;i<activityTblPos.size();i++){
            ActivityTblPo activityTblPo = activityTblPos.get(i);
            //视频
            if(activityTblPo.getResList().size()>0 && activityTblPo.getResList().get(0).getType() == 2){
                result.get(i).setVideoUrl(activityTblPo.getResList().get(0).getUrl());
                result.get(i).setDuration(activityTblPo.getResList().get(0).getDuration());
            }else {
                List<String> photos = new ArrayList<>();
                for (ActivityResPo activityResPo : activityTblPo.getResList()){
                    photos.add(activityResPo.getUrl());
                }
                result.get(i).setPhotos(photos);
            }
            if(activityTblPo.getCreatorId().equals(userid)){
                List<User> userList = activityMapper.selectActivityParticipate(activityTblPo.getId());
                result.get(i).setUserList(userList);
            }
        }

        return Result.success(result);
    }



    /**
     * 获取我参加的活动
     * @param page
     * @return
     */
    @Override
    public List<ActivityInfo> getActivitiesIParticipated(Integer page) {
        Long userid = LocalUser.getUser().getUser().getId();
        List<ActivityTblPo> activityTblPos = activityMapper.getActivitiesIParticipated((page - 1) * 10, userid);
        List<ActivityInfo> result = JSONArray.parseArray(JSONArray.toJSONString(activityTblPos),ActivityInfo.class);
        for(int i=0;i<activityTblPos.size();i++){
            ActivityTblPo activityTblPo = activityTblPos.get(i);
            //视频
            if(activityTblPo.getResList().size()>0 && activityTblPo.getResList().get(0).getType() == 2){
                result.get(i).setVideoUrl(activityTblPo.getResList().get(0).getUrl());
                result.get(i).setDuration(activityTblPo.getResList().get(0).getDuration());
            }else {
                List<String> photos = new ArrayList<>();
                for (ActivityResPo activityResPo : activityTblPo.getResList()){
                    photos.add(activityResPo.getUrl());
                }
                result.get(i).setPhotos(photos);
            }
            if(activityTblPo.getCreatorId().equals(userid)){
                List<User> userList = activityMapper.selectActivityParticipate(activityTblPo.getId());
                result.get(i).setUserList(userList);
            }
        }

        return result;
    }

    /**
     * 参加活动
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor=Exception.class)
    public Result participateActivity(Long id){

        ActivityParticipateTbl selectOne = new ActivityParticipateTbl();//先查之前又没有参加
        selectOne.setUserId(LocalUser.getUser().getUser().getId());
        selectOne.setActivityId(id);
        selectOne.setCancel(false);
        ActivityParticipateTbl activityParticipateTbl = activityParticipateTblMapper.selectOne(selectOne);
        if(activityParticipateTbl==null){//之前没参加
            ActivityParticipateTbl delete = new ActivityParticipateTbl();//先删除之前的记录
            delete.setUserId(LocalUser.getUser().getUser().getId());
            delete.setActivityId(id);
            activityParticipateTblMapper.delete(delete);
            ActivityParticipateTbl insertSelective = new ActivityParticipateTbl();//再添加
            insertSelective.setUserId(LocalUser.getUser().getUser().getId());
            insertSelective.setActivityId(id);
            insertSelective.setParticipateTime(new Date());
            int boo = activityParticipateTblMapper.insertSelective(insertSelective);
            //参加人数计数加一
            activityMapper.updeteJoinMemberNum(id,boo);
        }
        return Result.success();
    }

    /**
     * 取消参加活动
     * @param id
     */
    @Override
    @Transactional(rollbackFor=Exception.class)
    public void cancelParticipateActivity(Long id){
        int boo = activityMapper.cancelParticipateActivity(new Date(),id, LocalUser.getUser().getUser().getId());
        //取消成功参加人减一
        if(boo == 1){
            activityMapper.updeteJoinMemberNum(id,-1);
        }
    }

    /**
     * 封面
     * @param image
     * @return
     */
    @Override
    @Transactional(rollbackFor=Exception.class)
    public boolean cover(MultipartFile image){
        try {

            String url = UploadTempUtil.uploadImg(image,LocalUser.getUser().getToken());

            ActivityCoverTbl cover = getCoverTbl();
            if(cover!=null){
                cover.setUrl(url);
                activityCoverTblMapper.updateByPrimaryKey(cover);
            }else {
                ActivityCoverTbl activityCoverTbl = new ActivityCoverTbl();
                activityCoverTbl.setUserId(GlobalController.getNowUser().getId());
                activityCoverTbl.setUrl(url);
                activityCoverTblMapper.insertSelective(activityCoverTbl);
            }

        } catch (IOException e) {
            e.printStackTrace();
            throw new UserException(StatusCode.INTERNAL_SERVER_ERROR);
        }
        return true;
    }
    /**
     * 获取自己的活动封面URl
     * @return
     */
    @Override
    public String getCover(){

        ActivityCoverTbl activityCoverTbl = getCoverTbl();
        if(activityCoverTbl!=null){
            return activityCoverTbl.getUrl();
        }
        return null;
    }

    /**
     * 获取自己的活动封面
     * @return
     */
    private ActivityCoverTbl getCoverTbl(){
        ActivityCoverTbl select = new ActivityCoverTbl();
        select.setUserId(GlobalController.getNowUser().getId());
        return activityCoverTblMapper.selectOne(select);
    }

    /**
     * 获取已读最新ID
     * @return
     */
    @Override
    public Long getRead(){
        ActivityReadTbl activityReadTbl = new ActivityReadTbl();
        activityReadTbl.setUserId(GlobalController.getNowUser().getId());
        activityReadTbl = activityReadTblMapper.selectOne(activityReadTbl);

        if(activityReadTbl!=null){
            return activityReadTbl.getActivityId();
        }
        return 0L;
    }

    /**
     * 修改已读最新ID
     * @param readId
     */
    @Override
    public void putRead(Long readId){
        ActivityReadTbl activityReadTbl = new ActivityReadTbl();
        activityReadTbl.setUserId(GlobalController.getNowUser().getId());
        activityReadTbl = activityReadTblMapper.selectOne(activityReadTbl);

        if(activityReadTbl!=null){
            activityReadTbl.setActivityId(readId);
            activityReadTblMapper.updateByPrimaryKey(activityReadTbl);
        }else {
            activityReadTbl = new ActivityReadTbl();
            activityReadTbl.setUserId(GlobalController.getNowUser().getId());
            activityReadTbl.setActivityId(readId);
            activityReadTblMapper.insertSelective(activityReadTbl);
        }
    }

    /**
     * 修改已读最新ID
     * @return
     */
    @Override
    public int unreadNum(){
        ActivityReadTbl activityReadTbl = new ActivityReadTbl();
        activityReadTbl.setUserId(GlobalController.getNowUser().getId());
        activityReadTbl = activityReadTblMapper.selectOne(activityReadTbl);
        if(activityReadTbl!=null){
            Example example = new Example(ActivityTbl.class);
            example.createCriteria() .andGreaterThan("id", activityReadTbl.getActivityId())
                    .andEqualTo("deleted",false);

            int count = activityTblMapper.selectCountByExample(example);
            return count;
        }else {
            Example example = new Example(ActivityTbl.class);
            example.createCriteria().andEqualTo("deleted",false)
                    .andGreaterThan("id", 0);
            int count = activityTblMapper.selectCountByExample(example);
            return count;
        }
    }
}
